<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { fieldApi } from '@/api/fieldApi'
import PageHeader from '@/components/PageHeader.vue'
import BasePagination from '@/components/BasePagination.vue'
import SearchBar from '@/components/SearchBar.vue'

const loading = ref(false)
const fields = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = computed(() => window.innerWidth > 768 ? 20 : 10)

// 搜索条件
const searchForm = reactive({
  name: ''
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: null,
  name: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入字段名称', trigger: 'blur' }]
}

// 计算属性：是否为PC端
const isPC = ref(window.innerWidth > 768)

// 获取字段列表
const fetchFields = async () => {
  try {
    loading.value = true;
    const response = await fieldApi.getFields({
      page: currentPage.value,
      limit: pageSize.value,
      name: searchForm.name
    });
    
    // 确保 fields 是一个数组
    if (response.code === 200 && response.data) {
      fields.value = Array.isArray(response.data.items) ? response.data.items : [];
      total.value = response.data.total || 0;
    } else {
      fields.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取字段列表失败:', error);
    ElMessage.error('获取字段列表失败：' + error.message);
    fields.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 监听窗口大小变化
const handleResize = () => {
  isPC.value = window.innerWidth > 768
  fetchFields()
}

// 修改重置方法
const handleReset = () => {
  searchForm.name = ''
  currentPage.value = 1
  fetchFields()
}

// 处理搜索
const handleSearch = async () => {
  currentPage.value = 1
  await fetchFields()
}

// 处理页码变化
const handleCurrentChange = val => {
  currentPage.value = val
  fetchFields()
}

// 处理添加字段
const handleAdd = () => {
  dialogType.value = 'add'
  form.id = null
  form.name = ''
  dialogVisible.value = true
}

// 处理编辑字段
const handleEdit = row => {
  // 系统字段不可编辑（ID 1-8）
  if (row.id <= 8) {
    ElMessage.warning('系统字段不可编辑')
    return
  }
  dialogType.value = 'edit'
  form.id = row.id
  form.name = row.name
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 检查字段名称是否为空
    if (!form.name?.trim()) {
      ElMessage.warning('请输入字段名称')
      return
    }

    // 生成field_name：使用 field_ 前缀加时间戳
    const timestamp = Date.now()
    const field_name = `field_${timestamp}`
    
    const data = {
      name: form.name.trim(),
      field_name
    }

    const response = await fieldApi[dialogType.value === 'add' ? 'createField' : 'updateField'](
      dialogType.value === 'add' ? data : { id: form.id, ...data }
    )

    if (response.code === 200) {
      ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      fetchFields()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('Submit field error:', error)
    const errorMessage = error.response?.data?.message || error.message || '操作失败'
    ElMessage.error(dialogType.value === 'add' ? `添加失败: ${errorMessage}` : `更新失败: ${errorMessage}`)
  }
}

// 处理删除字段
const handleDelete = async row => {
  // 系统字段不可删除（ID 1-8）
  if (row.id <= 8) {
    ElMessage.warning('系统字段不可删除')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除字段"${row.name}"吗？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await fieldApi.deleteField(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchFields()
    }
  } catch (error) {
    if (error === 'cancel') return
    
    console.error('删除字段失败:', error)
    // 获取错误信息
    let errorMessage = '删除失败'
    if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message && !error.message.includes('服务器内部错误')) {
      errorMessage = error.message
    }
    
    // 根据错误类型显示不同的提示
    if (error.response?.status === 403 || errorMessage.includes('证书使用') || errorMessage.includes('系统字段')) {
      ElMessage({
        type: 'warning',
        message: errorMessage,
        duration: 5000,
        showClose: true
      })
    } else {
      ElMessage.error({
        message: errorMessage,
        duration: 3000,
        showClose: true
      })
    }
  }
}

// 初始化
onMounted(() => {
  fetchFields()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <el-card class="field-list">
    <!-- 头部区域 -->
    <template #header>
      <page-header title="字段管理">
        <el-button type="primary" @click="handleAdd">添加字段</el-button>
      </page-header>
    </template>

    <!-- 搜索栏 -->
    <search-bar
      v-model="searchForm.name"
      placeholder="输入字段名称搜索"
      :clearable="true"
      width="300px"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 字段列表 -->
    <div class="field-table" v-loading="loading">
      <!-- 表格部分 -->
      <div class="desktop-table" v-if="isPC">
        <el-table
          v-loading="loading"
          :data="fields"
          border
          style="width: 100%"
        >
          <el-table-column label="序号" width="120" align="center" :resizable="false">
            <template #default="{ row }">
              {{ row.sequence_number || row.id }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="字段名称" min-width="120" align="center" :resizable="false" />
          <el-table-column label="操作" width="225" align="center" :resizable="false">
            <template #default="{ row }">
              <span v-if="row.id <= 8" class="system-field-tag">系统字段</span>
              <template v-else>
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- PC端分页器 -->
      <base-pagination
        v-if="isPC"
        v-model:current-page="currentPage"
        :total="total"
        :page-size="20"
        @update:current-page="handleCurrentChange"
      />

      <!-- 移动端卡片列表 -->
      <div v-else class="mobile-cards">
        <div v-loading="loading">
          <div v-for="field in fields" :key="field.id" class="field-card">
            <div class="card-main">
              <div class="field-info">
                <span class="field-index">{{ field.sequence_number || field.id }}</span>
                <span class="divider">|</span>
                <span class="field-name">{{ field.name }}</span>
              </div>
              <div class="card-actions">
                <span v-if="field.id <= 8" class="system-field-tag">系统字段</span>
                <template v-else>
                  <el-button type="primary" link @click="handleEdit(field)">编辑</el-button>
                  <el-button type="danger" link @click="handleDelete(field)">删除</el-button>
                </template>
              </div>
            </div>
          </div>
        </div>

        <!-- 移动端分页器 -->
        <base-pagination
          v-model:current-page="currentPage"
          :total="total"
          :page-size="10"
          @update:current-page="handleCurrentChange"
        />
      </div>

      <!-- 添加/编辑字段对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '添加字段' : '编辑字段'"
        width="500px"
        @close="formRef?.resetFields()"
      >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="字段名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入字段名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-card>
</template>

<style lang="scss" scoped>
.field-list {
  height: 100%;
  margin: -20px;
  display: flex;
  flex-direction: column;
  
  :deep(.el-card__header) {
    padding: 0;
    border-bottom: 1px solid var(--el-border-color-light);
  }

  :deep(.el-card__body) {
    padding: 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .field-table {
      flex: 1;
      overflow-y: auto;
    }
  }
}

/* 表格样式 */
.field-table {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.desktop-table {
  padding: 20px;
  
  :deep(.el-table) {
    --el-table-border-color: #e4e7ed;
    --el-table-header-bg-color: #f5f7fa;
    
    .el-table__header th {
      background-color: var(--el-table-header-bg-color);
      color: #606266;
      font-weight: 500;
      height: 44px;
    }
    
    .el-table__row td {
      padding: 12px 0;
    }
  }
}

/* 移动端卡片列表样式 */
.mobile-cards {
  padding: 12px;
  
  .field-card {
    background: #fff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 12px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .card-main {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .field-info {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .field-index {
        color: #606266;
        font-size: 14px;
      }
      
      .field-name {
        color: #303133;
        font-weight: 500;
      }
    }
    
    .card-actions {
      display: flex;
      gap: 8px;
    }
  }
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .common-search-bar {
    padding: 12px;
  }
  
  .mobile-cards {
    padding: 12px;
  }
}

/* 全局文本样式 */
.text-regular {
  font-family: var(--el-font-family);
  font-size: var(--el-font-size-base);
  color: var(--el-text-color-regular);
  font-weight: var(--el-font-weight-primary);
}

/* 系统字段标签样式 */
.system-field-tag {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #91d5ff;
  font-size: 12px;
}
</style>